package com.serverdemo.core.net;

import com.serverdemo.core.entity.SocketEntity;
import com.serverdemo.core.entity.SocketEntityStatusEnum;
import com.serverdemo.core.processor.AbstractProcessor;
import com.serverdemo.core.processor.ProcessorManager;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

/**
 * Created by wangqiang on 2020/4/9.
 */
public class PacketHandler extends ChannelInboundHandlerAdapter
{
    private SocketEntity socketEntity;

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception
    {
        super.channelActive(ctx);

        if (socketEntity == null)
        {
            socketEntity = new SocketEntity();
            socketEntity.setChannel(ctx.channel());
        }

        // 发送给登录线程
        AbstractProcessor loginProcessor = ProcessorManager.getInstance().getLoginProcessor();
        loginProcessor.addSocketEntity(socketEntity);
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception
    {
        super.channelInactive(ctx);
        socketEntity.setStatusEnum(SocketEntityStatusEnum.EXCEPTION);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception
    {
        super.channelRead(ctx, msg);

        socketEntity.pushReceivedPacket((NetPacket) msg);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception
    {
        super.exceptionCaught(ctx, cause);
        socketEntity.setStatusEnum(SocketEntityStatusEnum.EXCEPTION);
    }
}
